using PKGames.Analytics;
using PKGames.Audio;
using PKGames.Localization;
using UnityEngine;

namespace PKGames
{
	public abstract class BaseGameController : MonoBehaviour
	{
		[SerializeField]
		private GameObject _rootGameObject;

		[SerializeField]
		private SupportedLocalization _supportedLocalization;

		protected Language _currentLanguage = Language.English;

		protected bool _isMuted;

		private string _analyticsName;

		private string _analyticsPack;

		private string _analyticsOrigin;

		private PlayGameEventController _playGameEventController;

		protected void Init(string gameName, string packName, string origin = "world_selector")
		{
			_analyticsName = gameName;
			_analyticsPack = packName;
			_analyticsOrigin = origin;
			_playGameEventController = new PlayGameEventController(gameName, packName, origin);
		}

		protected virtual void OnDestroy()
		{
			if (MonoSingleton<AudioManager>.Instance != null)
			{
				MonoSingleton<AudioManager>.Instance.StopBackgroundMusic();
				MonoSingleton<AudioManager>.Instance.StopAllSounds();
				MonoSingleton<AudioManager>.Instance.Cleanup();
			}
			LogPlayed();
		}

		protected void ResolveLanguage()
		{
			MonoSingleton<LocationProvider>.Instance.ResolveLanguage();
			string language = MonoSingleton<LocationProvider>.Instance.GetLanguage();
			Language language2 = Language.FromString(language);
			foreach (GameLocalization localization in _supportedLocalization.Localizations)
			{
				Language b = Language.FromInt((int)localization.Language);
				if (language2 == b)
				{
					_currentLanguage = language2;
				}
			}
			foreach (GameLocalization localization2 in _supportedLocalization.Localizations)
			{
				Language a = Language.FromInt((int)localization2.Language);
				if (a == _currentLanguage)
				{
					GameObject gameObject = UnityEngine.Object.Instantiate(localization2.AudioCollection.Asset<GameObject>());
					AttachToRoot(gameObject.transform);
					break;
				}
			}
		}

		public void AttachToRoot(Transform t)
		{
			t.transform.SetParent(_rootGameObject.transform);
		}

		public Transform GetRootTransform()
		{
			return _rootGameObject.transform;
		}

		protected virtual void OnBack()
		{
		}

		protected void OnApplicationPause(bool pause)
		{
			if (pause)
			{
				LogPlayed();
			}
			else
			{
				RestartAnalytics();
			}
		}

		protected virtual void LogPlayed()
		{
			_playGameEventController.LogEvent();
		}

		protected virtual void RestartAnalytics()
		{
			_playGameEventController = new PlayGameEventController(_analyticsName, _analyticsPack, _analyticsOrigin);
		}
	}
}
